package com.emep.changzhi.analyse.config;

import com.emep.changzhi.analyse.entity.systeminfo.SysMenuInfo;
import com.emep.changzhi.analyse.entity.systeminfo.SysRoleInfo;
import com.emep.changzhi.analyse.entity.systeminfo.SysUserInfo;
import com.emep.changzhi.analyse.repository.systeminfo.SysUserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by nydiarra on 06/05/17.
 */
@Component
public class AppUserDetailsService implements UserDetailsService {
    @Autowired
    private SysUserInfoRepository sysUserInfoRepository;

    @Autowired
    private RedisClient redisClient;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        SysUserInfo user = sysUserInfoRepository.findSysUserInfoByPhone(phone);
        if(user == null){
            throw new UsernameNotFoundException("账号："+ phone + "不存在！");
        }
        String yanz = redisClient.get(phone);
        user.setPassword(yanz);
        Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
        Iterator<SysRoleInfo> iterator =  user.getSysRoleInfos().iterator();
        while (iterator.hasNext()){
            Iterator<SysMenuInfo> sysMenuInfoIterator  = iterator.next().getSysMenuInfos().iterator();
            while (sysMenuInfoIterator.hasNext()) {
                collection.add(new SimpleGrantedAuthority(sysMenuInfoIterator.next().getMenuName()));
            }
        }

        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),collection);
    }
}
